import { Injectable } from '@nestjs/common';
import { daemonCmd } from './cmd';
import { cmdExec } from '../utils';

@Injectable()
export class DaemonService {
  async startDaemon(dev_id: string, is_hisi_gpu: boolean) {
    try {
      // 删除之前的端口映射
      await cmdExec(daemonCmd.hdc.delPort(dev_id));
      // 获取当前运行daemon的pid
      const pids = await cmdExec(daemonCmd.hdc.getPid(dev_id));
      // 干掉当前所有daemon进程
      const killRet = await cmdExec(
        daemonCmd.hdc.killPid(dev_id, pids.toString()),
      );
      if (killRet.toString().includes('Permission denied')) {
        // user版本权限管控，不能kill进程，不再重新拉起新进程
        console.log('kill daemon pid Permission denied');
      }
      // 拉起daemon服务
      await cmdExec(daemonCmd.hdc.startSystemServer(dev_id));
      // 建立新的端口映射
      await cmdExec(daemonCmd.hdc.setPort(dev_id));
    } catch (err) {
      console.debug('err', err);
    }

    if (is_hisi_gpu) {
      console.log('is_hisi_gpu', is_hisi_gpu);
    }
  }
}
